package com.datastory.report.controller;

import com.datastory.report.config.AppConfig;
import com.datastory.report.dto.FileView;
import com.datastory.report.utils.HtmlStrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;

/**
 * @author hshe 2018/6/13.
 */
@ResponseBody
@RestController
public class FileController {


    @Autowired
    AppConfig config;

    //    @RequestMapping("/download")
    public String downloadFile(File file, HttpServletResponse response) {
//        String fileName = request.getParameter("filename");
        try {
            if (file.exists()) {
                String fileName = file.getName();
                // 设置强制下载不打开
                response.setContentType("text/html;charset=UTF-8");
                response.setContentType("application/force-download;charset=utf-8");
                String final_filename = fileName.substring(fileName.lastIndexOf("/") + 1);
                final_filename = new String(final_filename.getBytes(), "ISO-8859-1");
                response.addHeader("Content-Disposition", "attachment;fileName=" + final_filename);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    ServletOutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("success!");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (null != bis) {
                        bis.close();
                    }
                    if (null != fis) {
                        fis.close();
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/index")
    public String index() {
        return null;
    }

    @GetMapping
    public void listFiles2(HttpServletRequest request, HttpServletResponse response) {
//        System.out.println(request.getRequestURI());
//        System.out.println("==========here===========");
//        return listFiles(request, response);
        showFiles(request, response);
    }


    public void showFiles(HttpServletRequest request, HttpServletResponse response) {
        try {
//            System.out.println(request.getRequestURI());
            String gbk_url = URLDecoder.decode(request.getRequestURI(), "UTF-8");
            System.out.println(gbk_url);


//            String path = request.getRequestURI();
            gbk_url = gbk_url.replace("/report_war", "");
            File file = new File(config.getPath() + gbk_url);
            if (!file.exists()) {
                file = new File(config.getPath());
                gbk_url = "/";
            }
            if (file.isFile()) {
                downloadFile(file, response);
            } else {
                String htmlByFile = HtmlStrUtils.getHtmlByFile(file, gbk_url);
                response.setContentType("text/html; charset=utf-8");
                response.getWriter().write(htmlByFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    @RequestMapping(value = "404")
//    @ResponseStatus(value = HttpStatus.NOT_FOUND)
//    public String test(HttpServletRequest request, HttpServletResponse response, String path) {
//        System.out.println(path);
//        return listFiles(request, response);
//    }

    @RequestMapping("/list")
    public String listFiles(HttpServletRequest request, HttpServletResponse response) {
        try {
            String dirName = request.getParameter("filename");
            if (null == dirName) {
                dirName = "";
            }
            File file = new File(config.getPath() + dirName);

            response.setContentType("text/html; charset=utf-8");
            if (file.exists()) {
                File[] files = file.listFiles();
                PrintWriter writer = response.getWriter();


                ArrayList<FileView> fs = new ArrayList<>();

                for (File f : files) {

                    long l = f.lastModified();
                    long length = f.length();


                    if (f.isFile()) {
                        writer.write(HtmlStrUtils.getHtml(dirName, f.getName(), "download"));
                    } else {//文件夹
                        String content = HtmlStrUtils.getHtml(f.getName(), "list");
                        writer.write(content);
                    }
                }
            } else {
                response.getWriter().write("文件夹为空!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
